package com.tticar.invmanager.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.utils.MyResponseBody;
import com.tticar.invmanager.common.utils.date.DateStyle;
import com.tticar.invmanager.common.utils.date.DateUtil;
import com.tticar.invmanager.entity.PPurchase;
import com.tticar.invmanager.entity.SysUser;
import com.tticar.invmanager.entity.WRelativeUnit;
import com.tticar.invmanager.entity.vo.DictCodes;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.entity.vo.PurchaseAddDto;
import com.tticar.invmanager.entity.vo.PurchaseGoodsDto;
import com.tticar.invmanager.service.IPPurchaseService;
import com.tticar.invmanager.service.IPurchaseReturnService;
import com.tticar.invmanager.service.ISysUserService;
import com.tticar.invmanager.service.IWRelativeUnitService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.tticar.invmanager.entity.PurchaseReturn;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 退货单表 前端控制器
 * </p>
 *
 * @author joeyYan
 * @since 2018-12-21
 */
@Controller
@RequestMapping("/purchaseReturn")
public class PurchaseReturnController extends BaseController {

    @Autowired
    private IPurchaseReturnService purchaseReturnService;
    @Autowired
    private IWRelativeUnitService relativeUnitService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IPPurchaseService purchaseService;


    @PostMapping
    @ResponseBody
    public MyResponseBody post(PurchaseReturn purchaseReturn) {
        purchaseReturnService.insertOrUpdate(purchaseReturn);
        return MyResponseBody.success();
    }

    @PostMapping("delete")
    @ResponseBody
    public MyResponseBody delete(@RequestParam("codes[]") List<String> codes) {
        MyResponseBody responseBody = MyResponseBody.success();
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("code", codes.get(0));
        List<PurchaseReturn> purchaseReturns = purchaseReturnService.selectList(wrapper);
        List<Long> ids = new ArrayList<>();
        for (PurchaseReturn entity : purchaseReturns) {
            ids.add(entity.getId());
        }
        purchaseReturnService.delete(ids);
        Wrapper wrapper1 = new EntityWrapper<>();
        wrapper1.eq("return_order", codes.get(0));
        PPurchase pPurchase = purchaseService.selectOne(wrapper1);
        if (pPurchase != null) {
            pPurchase.setOrderStatus(1);
            pPurchase.setReturnOrder(null);
            purchaseService.updateById(pPurchase);
        }

        return responseBody;
    }

    @GetMapping("{id}")
    @ResponseBody
    public MyResponseBody get(@PathVariable("id") Long id) {
        MyResponseBody responseBody = MyResponseBody.success();
        responseBody.setData(purchaseReturnService.selectById(id));
        return responseBody;
    }

    @GetMapping("edit")
    public String edit(PurchaseReturn purchaseReturn, ModelMap modelMap) {
        modelMap.put("id", purchaseReturn.getId());
        return "/purchaseReturn/purchaseReturn_edit";
    }

    @GetMapping("list")
    @ResponseBody
    public Page list(PurchaseReturn purchaseReturn, MyPage<PurchaseReturn> page) {
        return purchaseReturnService.selectPage(purchaseReturn, page);
    }

    @GetMapping
    public String index(String searchText,ModelMap modelMap) {
        modelMap.put("searchText", searchText);
        return "/purchaseReturn/purchaseReturn";
    }

    @GetMapping("detailGoodsList")
    @ResponseBody
    public List<Map> detailList(String code) {
        List<Map> purchaseDetailList = this.purchaseReturnService.detailGoodsList(code);
        return purchaseDetailList;
    }

    @RequestMapping("addPurchaseReturn")
    public String addPurchase(HttpServletRequest request,ModelMap modelMap) {
        long timeToken = System.currentTimeMillis();
        modelMap.put("addPurchaseReturnToken", String.valueOf(timeToken));
        request.getSession().setAttribute("purchaseReturnToken",String.valueOf(timeToken));
        return "/purchaseReturn/purchaseReturnAdd";
    }

    /**
     * 新增退货单
     * */
    @PostMapping(value = "addRecord", produces="application/json;charset=UTF-8")
    @ResponseBody
    public MyResponseBody addRecord(PurchaseAddDto dto, String goods,HttpServletRequest request) throws ParseException {
        if (request.getSession().getAttribute("purchaseReturnToken") == null ||
                !request.getSession().getAttribute("purchaseReturnToken").toString().equals(dto.getToken())) {
            throw new MyServiceException("提交已受理，请勿重复提交");
        }
        request.getSession().removeAttribute("purchaseReturnToken");
        MyResponseBody responseBody = MyResponseBody.success();
        List<PurchaseGoodsDto> goodsList = JSONArray.parseArray(goods, PurchaseGoodsDto.class);
        dto.setGoodsList(goodsList);
        purchaseReturnService.addPurchaseReturn(dto);
        return responseBody;
    }

    @GetMapping("detailPage")
    public String detailPage(@RequestParam("purchaseReturnCode") String purchaseReturnCode,ModelMap modelMap) {
        modelMap.put("purchaseId", purchaseReturnCode);
        Wrapper w = new EntityWrapper<>();
        w.eq("code", purchaseReturnCode);
        List<PurchaseReturn> purchaseReturns = purchaseReturnService.selectList(w);
        BigDecimal totalMoney = BigDecimal.ZERO;
        for (PurchaseReturn dto : purchaseReturns) {
            totalMoney = totalMoney.add(dto.getUnitPrice().multiply(new BigDecimal(dto.getCount())));
        }
        PurchaseReturn purchaseReturn = purchaseReturns.get(0);
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", purchaseReturn.getRelativeId());
        WRelativeUnit wRelativeUnit = relativeUnitService.selectOne(wrapper);
        if (wRelativeUnit != null) {
            modelMap.put("relative", wRelativeUnit.getName());
        }
        Wrapper wrapper1 = new EntityWrapper<>();
        wrapper1.eq("username", purchaseReturn.getUsername());
        SysUser sysUser = userService.selectOne(wrapper1);
        if (sysUser != null) {
            modelMap.put("username", sysUser.getNickname());
        }
        modelMap.put("purchase", purchaseReturn);
        if ( purchaseReturn.getPayStatus() == 0 && purchaseReturn.getRepositoryStatus() == 0) {
            modelMap.put("otherMoney", 1);
        } else {
            modelMap.put("otherMoney", 0);
        }

        if (purchaseReturn.getPayStatus() == 1) {
            modelMap.put("payStatus", "已结清");
        } else {
            modelMap.put("payStatus", "未结清");
        }
        if (purchaseReturn.getRepositoryStatus() == 0) {
            modelMap.put("orderStatus", "未出库");
        } else if (purchaseReturn.getRepositoryStatus() == 1) {
            modelMap.put("orderStatus", "已出库");
        }

        if (purchaseReturn.getPayStatus() == 0 && purchaseReturn.getRepositoryStatus() == 1) {
            modelMap.put("moneyMessage", 1);
        }
        modelMap.put("ptime", DateUtil.DateToString(purchaseReturn.getOrderTime(), DateStyle.YYYY_MM_DD));
        modelMap.put("ctime", DateUtil.DateToString(purchaseReturn.getCtime(), DateStyle.YYYY_MM_DD_HH_MM_SS));

        modelMap.put("totalMoney", totalMoney.toString());
        modelMap.put("hasPay", purchaseReturn.getRealPay().toString());
        modelMap.put("needPay", purchaseReturn.getNeedPay() == null ? "0": purchaseReturn.getNeedPay().toString());

        if (purchaseReturn.getPayStatus() == 0 && purchaseReturn.getRepositoryStatus() != 0) {
            modelMap.put("endCount", 1);
            modelMap.put("otherMoney", -1);
        }
        if (purchaseReturn.getPayStatus() == 1) {
            modelMap.put("endCount", 2);
        }
        return "/purchaseReturn/new/purchaseReturnDetailWindow";
    }

    @PostMapping("detailList")
    @ResponseBody
    public List<Map> detailListByDetail(String purchaseReturnCode) {
        List<Map> purchaseDetailList = this.purchaseReturnService.getPurchaseDetailList(purchaseReturnCode);

        return purchaseDetailList;
    }

    /**
     * 窗口版出库，支持更改数量和实际进价
     * */
    @PostMapping("outRepositoryFromWindow")
    @ResponseBody
    public MyResponseBody outRepositoryFromWindow(String purchaseReturnCode,String rows,BigDecimal realPay,BigDecimal totalMoney,
                                                 Integer payStatus,String remark) {
        MyResponseBody responseBody = MyResponseBody.success();
        List<PurchaseGoodsDto> goodsList = JSONArray.parseArray(rows, PurchaseGoodsDto.class);

        purchaseReturnService.outRepositoryNewVersion(purchaseReturnCode,goodsList,realPay,totalMoney,payStatus,remark);
        return responseBody;
    }

    /**
     * 撤销出库
     * */
    @PostMapping("cancelOutRepository")
    @ResponseBody
    public MyResponseBody cancelInPurchase(String purchaseReturnCode) {
        MyResponseBody responseBody = MyResponseBody.success();
        purchaseReturnService.cancelOutRepository(purchaseReturnCode);
        return responseBody;
    }

    /**
     * 撤销结算
     * */
    @PostMapping("cancelEndCount")
    @ResponseBody
    public MyResponseBody cancelEndCount(String purchaseReturnCode) {
        MyResponseBody responseBody = MyResponseBody.success();
        purchaseReturnService.cancelEndCount(purchaseReturnCode);
        return responseBody;
    }
    /**
     * 结算
     * */
    @PostMapping("endCountPurchaseReturn")
    @ResponseBody
    public MyResponseBody endCountPurchaseReturn(String purchaseReturnCode,BigDecimal realPay,BigDecimal totalMoney,
                                           Integer payStatus,String remark) {
        MyResponseBody responseBody = MyResponseBody.success();
        purchaseReturnService.endCountPurchaseReturn(purchaseReturnCode,realPay,totalMoney,payStatus,remark);
        return responseBody;
    }

    /**
     * 整单退货
     * */
    @PostMapping("allReturn")
    @ResponseBody
    public MyResponseBody allReturn(@RequestParam("id[]") List<Long> ids) {
        MyResponseBody responseBody = MyResponseBody.success();
        Long purchaseId = ids.get(0);
        String allReturnCode = purchaseReturnService.allReturn(purchaseId);
        responseBody.setData(allReturnCode);
        return responseBody;
    }
}
